package edu.mse.camel.client.core.idcache;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import org.eclipse.emf.common.util.TreeIterator;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.util.EcoreUtil;

import edu.mse.camel.client.core.plugin.Activator;
import edu.mse.camel.client.log.Debug;

public class SourceModelIDCache {

	private Map<EObject, ModelID> idCache;
	protected EObject modelRoot;
	private ModelID newID;
	
	public SourceModelIDCache(EObject modelRoot) {
		idCache = new HashMap<EObject, ModelID>();
		this.modelRoot = modelRoot;
		newID = null;
	}
	
	public void generateCache() {
		TreeIterator<EObject> iterator = 
			EcoreUtil.getAllContents(Collections.singleton(modelRoot));
		int i = 0;
		while (iterator.hasNext()) {
			EObject eObject = iterator.next();
			ModelID newID = new ModelID(i++);
			idCache.put(eObject, newID);
		}
		newID = new ModelID(i);
	}
	
	public ModelID getID(EObject eObject) {
		return idCache.get(eObject);
	}
	
	public void addElementRecursive(EObject eObject) {
		TreeIterator<EObject> iterator = 
			EcoreUtil.getAllContents(Collections.singleton(eObject));
		int i = newID.getID();
		while (iterator.hasNext()) {
			EObject childEObject = iterator.next();
			Debug.log_info(Activator.PLUGIN_ID, "Generating id for: " + EcoreUtil.getIdentification(childEObject));
			//ModelID newID = new ModelID(i++);
			idCache.put(childEObject, newID);
		}
		newID = new ModelID(i);
	}

}
